const path = require("path");

const Koa = require("koa");
const { koaBody } = require("koa-body");
const KoaStatic = require("koa-static");
const parameter = require("koa-parameter");

const errHandler = require("./errHandler");

const router = require("../router");

const app = new Koa();

app.use(
  koaBody({
    multipart: true,
    formidable: {
      maxFiles: 10,
      maxFileSize: 210 * 1024 * 1024,
      // 在配制选项option里, 不推荐使用相对路径
      // 在option里的相对路径, 不是相对的当前文件. 相对process.cwd()
      uploadDir: path.join(__dirname, "../upload"),
      keepExtensions: true,
      filter: function ({ name, originalFilename, mimetype }) {
        // default function that always returns true. Use it to filter files before they are uploaded. Must return a boolean. Will not make the form.parse error
        const fileTypes = ["image/jpeg", "image/png"];
        return mimetype && fileTypes.includes(mimetype);
      },
    },
    parsedMethods: ["POST", "PUT", "PATCH", "DELETE"],
  })
);

app.use(KoaStatic(path.join(__dirname, "../upload")));
app.use(parameter(app));

app.use(router.routes()).use(router.allowedMethods());

// 统一的错误处理
app.on("error", errHandler);

module.exports = app;
